﻿using CommonClass;
using I_Authorization.Domains;
using I_Authorization.Domains.Organization;
using I_Authorization.Domains.RBAC;
using I_Authorization.Infrastructure.Interface;
using I_Authorization.Read.API.Application.Commands.Role;
using MediatR;

namespace I_Authorization.Read.API.Application.CommandHandlers.Role
{
    /// <summary>
    /// 角色分页
    /// </summary>
    public class RoleShowCommandHandlers : IRequestHandler<RoleShowCommand, PageResult<RoleInfo>>
    {
        private readonly IRoleRepository _roleRepository;

        public RoleShowCommandHandlers(IRoleRepository roleRepository)
        {
            _roleRepository = roleRepository;
        }
        /// <summary>
        /// 分页显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PageResult<RoleInfo>> Handle(RoleShowCommand request, CancellationToken cancellationToken)
        {
            var list = await _roleRepository.GetAsync(x=>x.IsDel==true);

            if(!string.IsNullOrEmpty(request.RoleName)|| request.RoleName!=null)
            {
                list = list.Where(x => x.RoleName.Contains(request.RoleName)).ToList();
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            list = list.OrderByDescending(c=>c.RoleId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

            return new PageResult<RoleInfo>
            {
                TotalCount = totalCount,
                PageCount = pageCount,
                Datas = list
            };
        }
    }
}
